import React, { useEffect, useMemo } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { List, Button, NavBar, Popover, Tag } from "antd-mobile";
import { MoreOutline } from "antd-mobile-icons";
import { useRequest } from "ahooks";
import GroupChatCreator from "@/components/GroupChatCreator";
import { chatroom_info, chatroom_deluser, chatroom_delete } from "@/apis";
import { getState } from "@/store";
import * as hm from "@/handle_message";
import styles from "./index.less";
import ChatRoomName from './ChatRoomName'
import { Avatar } from "@/components/Avatar";

const ChatDetail = () => {
  const { loginUser, userMap } = getState();
  const { username: currentUsername } = loginUser || {};
  const navigate = useNavigate();
  const { id: chatroom_id } = useParams();

  const { data: currentRoomInfo, refresh } = useRequest(chatroom_info, { defaultParams: [{ _id: chatroom_id }] });

  const [members, is_master, is_controlled] = useMemo(() => {
    const users = currentRoomInfo?.data?.users;
    const members = [];
    let is_master = false;
    const is_controlled = currentRoomInfo?.data?.is_controlled;

    if (users) {
      for (const member of users) {
        if (member.username !== currentUsername) {
          members.push(member.username);
        } else {
          is_master = member.is_master;
        }
      }
    }

    return [members, is_master, is_controlled];
  }, [currentRoomInfo]);

  function remove(username) {
    chatroom_deluser({ _id: chatroom_id, users: [username] }).finally(() => {
      refresh();
    });
  }

  function dismiss() {
    chatroom_delete({ _id: chatroom_id }).finally(() => {
      navigate("/");
    });
  }

  function exit() {
    chatroom_deluser({ _id: chatroom_id, users: [currentUsername] }).finally(() => {
      navigate("/");
    });
  }

  const actions = is_master
    ? [
        {
          text: (
            <GroupChatCreator
              title="添加群成员"
              chatroom_id={chatroom_id}
              members={members}
              onOk={() => {
                refresh();
              }}
            >
              <span>添加群成员</span>
            </GroupChatCreator>
          ),
        },
        { text: <span onClick={dismiss}>解散群聊</span> },
      ]
    : [{ text: <span onClick={exit}>退出群聊</span> }];

  function chatroomDismiss() {}

  function chatroomMemberAdd() {
    refresh();
  }

  function chatroomMemberRemove({ users }) {
    if (users.includes(currentUsername)) {
      navigate("/");
    } else {
      refresh();
    }
  }

  function chatroomUpdate() {
    refresh();
  }
  useEffect(() => {
    hm.addEventListener("chatroom_adduser", chatroomMemberAdd);
    hm.addEventListener("chatroom_delete", chatroomDismiss);
    hm.addEventListener("chatroom_deluser", chatroomMemberRemove);
    hm.addEventListener("chatroom_update", chatroomUpdate)

    return () => {
      hm.addEventListener("chatroom_adduser", chatroomMemberAdd);
      hm.addEventListener("chatroom_delete", chatroomDismiss);
      hm.addEventListener("chatroom_deluser", chatroomMemberRemove);
      hm.addEventListener("chatroom_update", chatroomUpdate);
    };
  }, []);

  return (
    <>
      <NavBar
        className={styles["chat-detail-header"]}
        back="返回"
        onBack={() => {
          navigate(-1);
        }}
        right={
          !is_controlled && (
            <Popover.Menu actions={actions} placement="bottom-start" trigger="click">
              <MoreOutline fontSize={36} />
            </Popover.Menu>
          )
        }
      >
        群聊信息
      </NavBar>
      <List header="群聊名称">
        <List.Item>
          <ChatRoomName chatroom={currentRoomInfo?.data}/>
        </List.Item>
      </List>
      <List header="群成员" className={styles["group-member-list"]}>
        {currentRoomInfo?.data?.users?.map((user) => {
          const u = userMap.get(user.username)
          return (
            <List.Item
              key={user.username}
              prefix={<Avatar src={ u?.avatar } />}
              description={u?.group}
              extra={
                !is_controlled &&
                is_master &&
                user.username !== currentUsername && (
                  <Button
                    onClick={() => {
                      remove(user.username);
                    }}
                  >
                    移除
                  </Button>
                )
              }
            >
              {u?.name || user.username} {user.is_master ? <Tag round>群主</Tag> : (user.is_admin && <Tag round>管理员</Tag>)}
            </List.Item>
          )
        })}
      </List>
    </>
  );
};

export default ChatDetail;
